package com.suke.czx.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 应用模块名称: 工具类
 * 代码描述: Excel工具类
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/10/20 1:08
 */
@Slf4j
public class ExcelUtil {

    /**
     * 写excel文件
     * @param response 响应
     * @param sxssfWorkbook sxssfWorkbook
     * @param fileName 文件名
     */
    public static void writeExcel(HttpServletResponse response, SXSSFWorkbook sxssfWorkbook, String fileName) {
        // 设值Content-Type
        response.setContentType(ExportContentTypeEnum.EXCEL_2007.getFormat());
        // 设置编码
        response.setCharacterEncoding(ConfigConstant.CHARSET_UTF_8);
        OutputStream outputStream = null;
        try {
            // 获取输出流
            outputStream = response.getOutputStream();
            // 设值文件名
            response.setHeader(ConfigConstant.CONTENT_DISPOSITION, "attachment; filename=" +
                    new String(fileName.getBytes(), ConfigConstant.CHARSET_ISO8859_1) + ConfigConstant.EXCEL_2007_SUFFIX);
            sxssfWorkbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            log.error("SXSSFWork write error::", e);
        } finally {
            if (sxssfWorkbook != null) {
                // 处理SXSSFWorkbook导出excel时，产生的临时文件
                sxssfWorkbook.dispose();
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("outputStream close error::", e);
                }
            }
        }
    }

}
